package surfing.chatting.union;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import surfing.chatting.client.User;

public class Robot extends User {
	static String API_URL = "http://openapi.tuling123.com/openapi/api/v2";
	static String API_KEY = "5226fd30b10242738f0eee3be80fe410";
	static String API_ID = "610524";

	public Robot(String id, String name) {
		super(id, name);
	}

	public Robot(Map<String, Object> map) {
		super(map);
	}

	public Robot() {
		super();
	}

	public String talk(String msg) {
		String reply;
		reply = httpPost(getReqMsg(msg));
		reply = getText(reply);
		return reply;
	}

	private String getReqMsg(String text) {
		JSONObject packet = new JSONObject();
		JSONObject perception = new JSONObject();
		JSONObject inputText = new JSONObject();
		JSONObject userInfo = new JSONObject();

		packet.put("reqType", 0);

		inputText.put("text", new String(text.getBytes()));
		perception.put("inputText", inputText);
		packet.put("perception", perception);

		userInfo.put("apiKey", API_KEY);
		userInfo.put("userId", API_ID);
		packet.put("userInfo", userInfo);
		return packet.toString();
	}

	private String getText(String reply) {
		JSONObject jsonObject = new JSONObject(reply);
		JSONArray a = jsonObject.getJSONArray("results");
		jsonObject = a.getJSONObject(0);
		jsonObject = jsonObject.getJSONObject("values");
		reply = jsonObject.getString("text");
		return reply;
	}

	private String httpPost(String reqMsg) {
		BufferedWriter bw = null;
		BufferedReader br = null;
		StringBuffer result = new StringBuffer();
		try {
			URL url = new URL(API_URL);
			URLConnection conn = url.openConnection();
			HttpURLConnection hconn = (HttpURLConnection) conn;
			hconn.setRequestProperty("Content-Type", "application/json");
			hconn.setRequestProperty("x-adviewrtb-version", "2.1");
			hconn.setDoInput(true);
			hconn.setDoOutput(true);
			bw = new BufferedWriter(new OutputStreamWriter(hconn.getOutputStream(), "utf-8"));
			bw.write(reqMsg);
			bw.flush();
			hconn.connect();
			br = new BufferedReader(new InputStreamReader(hconn.getInputStream(), "utf-8"));
			String line;
			while ((line = br.readLine()) != null) {
				result.append(line);
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (bw != null) {
					bw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result.toString();
	}
}